package com.mall.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.address.entity.Address;
import com.mall.address.service.AddressService;
import com.mall.comment.entity.Comment;
import com.mall.comment.service.CommentService;
import com.mall.commondataformat.R;
import com.mall.dingdan.entity.Dingdan;
import com.mall.dingdan.service.DingdanService;
import com.mall.user.entity.User;
import com.mall.user.service.UserService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

import java.util.List;

import static com.mall.commonutils.ResultCode.*;
import static com.mall.commonutils.SessionStaticMes.USER_IN_SESSION;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2020-04-29
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private DingdanService dingdanService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private CommentService commentService;



    @PostMapping("/test")
    public R test(){
        User user = new User();
        user.setUsername("123");
        user.setPassword("123");
        return R.ok().data("user",userService.getById(user));
    }


    @PostMapping("/myinfo")
    public R getMyInfo(Long id,
                       HttpSession session){
        return R.ok().data("user",userService.getById(id));
    }

    //登录方法
    @ApiOperation("登录测试")
    @PostMapping("/login")
    public R userLogin(String username,
                       String password,
                       HttpSession session){

        //User user = (User) session.getAttribute(USER_IN_SESSION);
        if(username==null || password==null){
            return R.error().message(LOGIN_ERROR_MESSAGE);
        }
        User user = new User();
         //如果session中不存该用户
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("username", username);
            wrapper.eq("password",password);
            user = userService.getOne(wrapper);
            if(user == null){
                return R.error().message(LOGIN_ERROR_MESSAGE);
            }
            user.setPassword(null);
            session.setAttribute(USER_IN_SESSION,user);
            return R.ok().data("user", user);
    }

    //注册方法
    @ApiOperation("注册测试")
    @PostMapping("/register")
    public R userRegister(String username, String password){
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        if (user == null){
            return R.error().message("注册失败");
        }
        boolean res = userService.save(user);
        if(res){
            return R.ok().message("注册成功");
        }else {
            return R.error().message("注册失败");
        }
    }

    //修改信息方法
    @ApiOperation("修改用户信息")
    @PostMapping("/updateInfo")
    public R updateUser(int gender,int age,String phone,String address,HttpSession session){
        //从session中拿到当前user对象,对其进行更改
        User user =(User)session.getAttribute(USER_IN_SESSION);
        user.setGender(gender);
        user.setAge(age);
        user.setPhone(phone);


        boolean res = userService.updateById(user);
        if (res){
            return R.ok().message("修改成功");
        }else {
            return R.error().message("修改失败");
        }
    }

    //用户名查重方法
    @ApiOperation("用户名查重")
    @PostMapping("/checkUsername")
    public R checkUsername(String username){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);

        User user = userService.getOne(wrapper);

        if (user == null){
            return R.error().message("用户不存在");
        }else {
            return R.ok().message("用户已存在");
        }

    }

    //查询收货地址
    @ApiOperation("查询收货地址")
    @GetMapping("/getMyAddress/{page}")
    public R getMyAddress(@ApiParam(name = "page", value = "当前页码", required = true)
                          @PathVariable Integer page,
                          HttpSession session){
        User user = (User)session.getAttribute(USER_IN_SESSION);
        if (user == null){
            return R.error().message(USER_NOT_LOGIN);
        }
        Long userid=user.getId();
        Page<Address> addressPage = new Page<>(page,PAGE_LIMIT);

        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userid);

        addressService.page(addressPage,wrapper);
        List<Address> addresses = addressPage.getRecords();

        if (addressPage == null){
            return R.error().message("当前用户尚未添加地址");
        }
        return R.ok().data("userAddress",addresses);
    }


    //新增收货地址
    @ApiOperation("新增收货地址")
    @PostMapping("/addAddress")
    public R addAddress(String content,String phone,String name,HttpSession session){
        Long userid = ((User)session.getAttribute(USER_IN_SESSION)).getId();
        if (userid==null){
            return R.error().message(USER_NOT_LOGIN);
        }
        Address addressd = new Address();
        addressd.setUserId(userid);
        addressd.setContent(content);
        addressd.setName(name);
        addressd.setPhone(phone);

        boolean res = addressService.save(addressd);
        if (res){
            return R.ok().message("新增地址成功");
        }else{
            return R.error().message("新增地址失败");
        }
    }


    //删除收货地址
    @ApiOperation("删除收货地址")
    @PostMapping("/deleteAddress")
    public R deleteAddress(Long addressId,HttpSession session){
        Long userid = ((User)session.getAttribute(USER_IN_SESSION)).getId();
        if (userid == null){
            return R.error().message(USER_NOT_LOGIN);
        }
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("id",addressId);
        wrapper.eq("user_id",userid);
        boolean res = addressService.remove(wrapper);
        if (res){            return R.ok().message("删除地址成功");
        }else{
            return R.error().message("删除地址失败");
        }
    }

    //用户修改密码
    @ApiOperation("修改用户密码")
    @PostMapping("/changePwd")
    public R changePwd(String oldPwd,String newPwd,HttpSession session){
        if(session.getAttribute(USER_IN_SESSION)==null){
            return R.error().message(USER_NOT_LOGIN);
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id",((User)session.getAttribute(USER_IN_SESSION)).getId());
        wrapper.eq("password",oldPwd);
        User user = userService.getOne(wrapper);

        if(user == null){
            return R.error().message("密码错误");
        }else{
            user.setPassword(newPwd);
            userService.updateById(user);
            return R.ok().message("修改密码成功");
        }
    }

    //用户查询当前所有订单
    @ApiOperation("查询用户所有订单")
    @GetMapping("/getDingdan/{page}")
    public R getDingdan(@ApiParam(name = "page", value = "当前页码", required = true)
                        @PathVariable Integer page,
                        HttpSession session){
        if (session.getAttribute(USER_IN_SESSION)==null){
            return R.error().message(USER_NOT_LOGIN);
        }
        QueryWrapper<Dingdan> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",((User)session.getAttribute(USER_IN_SESSION)).getId());

        Page<Dingdan> dingdanPage = new Page<>(page,PAGE_LIMIT);
        dingdanService.page(dingdanPage,wrapper);

        List<Dingdan> dingdans = dingdanPage.getRecords();
        return R.ok().data("dingdan",dingdans);

        //List<Order> orders = orderService.list(wrapper);

    }

    //用户确认付款
    @ApiOperation("用户确认付款")
    @PostMapping("/pay")
    public R pay(Long orderId,HttpSession session){
        User user = (User)session.getAttribute(USER_IN_SESSION);
        if(user == null) {
            return R.error().message(USER_NOT_LOGIN);
        }
        QueryWrapper<Dingdan> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",user.getId());
        wrapper.eq("id",orderId);
        Dingdan dingdan = dingdanService.getOne(wrapper);
        dingdan.setIsPay(IS_PAY);
        boolean res = dingdanService.updateById(dingdan);
        if (res) {
            return R.ok().message("用户确认付款成功");
        } else {
            return R.error().message("用户确认付款失败");
        }
    }

    //用户确认收货
    @ApiOperation("用户确认收货")
    @PostMapping("/accept")
    public R confirmGet(Long orderId,HttpSession session){
        User user = (User)session.getAttribute(USER_IN_SESSION);
        if(user == null) {
            return R.error().message(USER_NOT_LOGIN);
        }
        QueryWrapper<Dingdan> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",user.getId());
        wrapper.eq("id",orderId);
        Dingdan dingdan = dingdanService.getOne(wrapper);
        dingdan.setIsAccept(IS_ACCEPT);
        boolean res = dingdanService.updateById(dingdan);
        if (res) {
            return R.ok().message("用户确认收货成功");
        } else {
            return R.error().message("用户确认收货失败");
        }

    }

    //用户追加评价
    @ApiOperation("用户追加评价")
    @PostMapping("/comment")
    public R confirmGet(Long productId,String content,HttpSession session){
        User user = (User)session.getAttribute(USER_IN_SESSION);
        if (user == null) {
            return R.error().message(USER_NOT_LOGIN);
        }
        Comment comment = new Comment();
        comment.setShangpinId(productId);
        comment.setUserId(user.getId());
        comment.setUsername(user.getUsername());
        comment.setContent(content);

        boolean res = commentService.save(comment);
        if (res) {
            return R.ok().message("新增评论成功");
        } else {
            return R.error().message("新增评论失败");
        }

    }


    //确认收获
    //确认付款


/*    @GetMapping("/test1")
    public R test1(HttpSession session){
        User user = (User)session.getAttribute(USER_IN_SESSION);

        System.out.println(user);

        return R.ok();
    }*/
}

